const API_BASE_URL = '/api/products';

// DOM 元素
const productListSection = document.getElementById('product-list');
const createProductSection = document.getElementById('create-product');
const editProductSection = document.getElementById('edit-product');
const searchProductSection = document.getElementById('search-product');
const productDetailsSection = document.getElementById('product-details');
const productsTableBody = document.querySelector('#products-table tbody');
const createProductForm = document.getElementById('create-product-form');
const editProductForm = document.getElementById('edit-product-form');
const refreshBtn = document.getElementById('refresh-btn');
const searchByIdBtn = document.getElementById('search-by-id-btn');
const searchByCodeBtn = document.getElementById('search-by-code-btn');
const searchByStatusBtn = document.getElementById('search-by-status-btn');
const searchByCategoryBtn = document.getElementById('search-by-category-btn');
const editProductBtn = document.getElementById('edit-product-btn');
const activateProductBtn = document.getElementById('activate-product-btn');
const deactivateProductBtn = document.getElementById('deactivate-product-btn');
const deleteProductBtn = document.getElementById('delete-product-btn');
const backBtn = document.getElementById('back-btn');
const cancelEditBtn = document.getElementById('cancel-edit');

let currentProductId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载商品列表
    loadProducts();
    
    // 导航链接事件监听
document.querySelector('a[href="index.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'index.html';
    });
    
    document.querySelector('a[href="supplier.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'supplier.html';
    });
    
    document.querySelector('a[href="#product-list"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(productListSection);
        hideElement(productDetailsSection);
    });
    
    document.querySelector('a[href="#create-product"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(createProductSection);
        hideElement(productDetailsSection);
    });
    
    document.querySelector('a[href="#search-product"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(searchProductSection);
        hideElement(productDetailsSection);
    });
    
    // 刷新按钮事件监听
    refreshBtn.addEventListener('click', loadProducts);
    
    // 创建商品表单提交事件监听
    createProductForm.addEventListener('submit', function(e) {
        e.preventDefault();
        createProduct();
    });
    
    // 编辑商品表单提交事件监听
    editProductForm.addEventListener('submit', function(e) {
        e.preventDefault();
        updateProduct();
    });
    
    // 搜索按钮事件监听
    searchByIdBtn.addEventListener('click', function() {
        const productId = document.getElementById('search-id').value;
        if (productId) {
            getProductById(productId);
        } else {
            alert('请输入商品ID');
        }
    });
    
    searchByCodeBtn.addEventListener('click', function() {
        const productCode = document.getElementById('search-code').value;
        if (productCode) {
            getProductByCode(productCode);
        } else {
            alert('请输入商品编码');
        }
    });
    
    searchByStatusBtn.addEventListener('click', function() {
        const status = document.getElementById('search-status').value;
        if (status !== '') {
            getProductsByStatus(status);
        } else {
            loadProducts();
        }
    });
    
    searchByCategoryBtn.addEventListener('click', function() {
        const categoryId = document.getElementById('search-category').value;
        if (categoryId) {
            getProductsByCategoryId(categoryId);
        } else {
            alert('请输入分类ID');
        }
    });
    
    // 详情页面按钮事件监听
    backBtn.addEventListener('click', function() {
        showSection(productListSection);
        hideElement(productDetailsSection);
    });
    
    editProductBtn.addEventListener('click', function() {
        if (currentProductId) {
            showEditForm(currentProductId);
        }
    });
    
    cancelEditBtn.addEventListener('click', function() {
        showSection(productListSection);
        hideElement(editProductSection);
    });
    
    activateProductBtn.addEventListener('click', function() {
        if (currentProductId) {
            activateProduct(currentProductId);
        }
    });
    
    deactivateProductBtn.addEventListener('click', function() {
        if (currentProductId) {
            deactivateProduct(currentProductId);
        }
    });
    
    deleteProductBtn.addEventListener('click', function() {
        if (currentProductId && confirm('确定要删除该商品吗？')) {
            deleteProduct(currentProductId);
        }
    });
});

// 显示指定的部分，隐藏其他部分
function showSection(section) {
    productListSection.classList.add('hidden');
    createProductSection.classList.add('hidden');
    editProductSection.classList.add('hidden');
    searchProductSection.classList.add('hidden');
    
    section.classList.remove('hidden');
}

// 隐藏元素
function hideElement(element) {
    element.classList.add('hidden');
}

// 显示元素
function showElement(element) {
    element.classList.remove('hidden');
}

// 显示编辑表单并填充数据
function showEditForm(productId) {
    // 获取商品详细信息
    fetch(`${API_BASE_URL}/${productId}`)
        .then(response => response.json())
        .then(product => {
            // 填充表单数据
            document.getElementById('edit-product-id').value = product.id;
            document.getElementById('edit-product-code').value = product.productCode;
            document.getElementById('edit-product-name').value = product.productName;
            document.getElementById('edit-category-id').value = product.categoryId;
            document.getElementById('edit-unit').value = product.unit;
            document.getElementById('edit-cost-price').value = product.costPrice;
            document.getElementById('edit-sale-price').value = product.salePrice;
            document.getElementById('edit-stock-quantity').value = product.stockQuantity;
            document.getElementById('edit-product-status').value = product.status;
            document.getElementById('edit-product-remark').value = product.remark || '';
            
            // 显示编辑表单
            showSection(editProductSection);
        })
        .catch(error => {
            console.error('获取商品信息失败:', error);
            alert('获取商品信息失败');
        });
}

// 更新商品
function updateProduct() {
    const productId = document.getElementById('edit-product-id').value;
    const productData = {
        id: productId,
        productCode: document.getElementById('edit-product-code').value,
        productName: document.getElementById('edit-product-name').value,
        categoryId: parseInt(document.getElementById('edit-category-id').value),
        unit: document.getElementById('edit-unit').value,
        costPrice: parseFloat(document.getElementById('edit-cost-price').value),
        salePrice: parseFloat(document.getElementById('edit-sale-price').value),
        stockQuantity: parseInt(document.getElementById('edit-stock-quantity').value),
        status: document.getElementById('edit-product-status').value,
        remark: document.getElementById('edit-product-remark').value
    };

    fetch(`${API_BASE_URL}/${productId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(productData)
    })
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error('更新失败');
        }
    })
    .then(data => {
        alert('商品更新成功');
        showSection(productListSection);
        loadProducts();
    })
    .catch(error => {
        console.error('更新商品失败:', error);
        alert('更新商品失败: ' + error.message);
    });
}

// 日期时间格式化
function formatDateTime(dateTime) {
    if (!dateTime) return '';
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN');
}

// 获取状态显示文本
function getStatusText(status) {
    const statusMap = {
        'ACTIVE': '上架',
        'INACTIVE': '下架'
    };
    return statusMap[status] || status;
}

// 获取状态样式类名
function getStatusClassName(status) {
    return `status-badge status-${status}`;
}

// 加载所有商品
function loadProducts() {
    fetch(API_BASE_URL)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(products => {
            renderProductsTable(products);
        })
        .catch(error => {
            console.error('加载商品失败:', error);
            alert('加载商品失败: ' + error.message);
            // 使用mock数据
            renderProductsTable(mockProducts);
        });
}

// 渲染商品表格
function renderProductsTable(products) {
    productsTableBody.innerHTML = '';
    
    if (!products || products.length === 0) {
        productsTableBody.innerHTML = '<tr><td colspan="11" style="text-align: center;">暂无商品数据</td></tr>';
        return;
    }
    
    products.forEach(product => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${product.id}</td>
            <td>${product.productCode}</td>
            <td>${product.productName}</td>
            <td>${product.categoryId}</td>
            <td>${product.unit}</td>
            <td>¥${(product.costPrice || 0).toFixed(2)}</td>
            <td>¥${(product.salePrice || 0).toFixed(2)}</td>
            <td>${product.stockQuantity || 0}</td>
            <td class="${getStatusClassName(product.status)}">${getStatusText(product.status)}</td>
            <td>${formatDateTime(product.createdTime)}</td>
            <td>
                <button class="btn btn-sm btn-primary view-details-btn" data-id="${product.id}">查看</button>
            </td>
        `;
        productsTableBody.appendChild(row);
    });
    
    // 添加查看详情的事件监听
    document.querySelectorAll('.view-details-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const productId = this.getAttribute('data-id');
            getProductById(productId);
        });
    });
}

// 创建商品
function createProduct() {
    const formData = new FormData(createProductForm);
    const productData = {};
    
    formData.forEach((value, key) => {
        // 转换数字类型
        if (key === 'categoryId' || key === 'stockQuantity') {
            productData[key] = parseInt(value) || 0;
        } else if (key === 'costPrice' || key === 'salePrice') {
            productData[key] = parseFloat(value) || 0;
        } else {
            productData[key] = value;
        }
    });
    
    fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(productData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('创建商品失败');
        }
        return response.json();
    })
    .then(product => {
        alert('商品创建成功');
        createProductForm.reset();
        loadProducts();
    })
    .catch(error => {
        console.error('创建商品失败:', error);
        alert('创建商品失败: ' + error.message);
    });
}

// 根据ID获取商品
function getProductById(productId) {
    fetch(`${API_BASE_URL}/${productId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取商品失败');
            }
            return response.json();
        })
        .then(product => {
            displayProductDetails(product);
        })
        .catch(error => {
            console.error('获取商品失败:', error);
            alert('获取商品失败: ' + error.message);
        });
}

// 根据编码获取商品
function getProductByCode(productCode) {
    fetch(`${API_BASE_URL}/code/${productCode}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取商品失败');
            }
            return response.json();
        })
        .then(product => {
            displayProductDetails(product);
        })
        .catch(error => {
            console.error('获取商品失败:', error);
            alert('获取商品失败: ' + error.message);
        });
}

// 根据状态获取商品
function getProductsByStatus(status) {
    fetch(`${API_BASE_URL}/status/${status}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取商品失败');
            }
            return response.json();
        })
        .then(products => {
            renderProductsTable(products);
        })
        .catch(error => {
            console.error('获取商品失败:', error);
            alert('获取商品失败: ' + error.message);
        });
}

// 根据分类获取商品
function getProductsByCategoryId(categoryId) {
    fetch(`${API_BASE_URL}/category/${categoryId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取商品失败');
            }
            return response.json();
        })
        .then(products => {
            renderProductsTable(products);
        })
        .catch(error => {
            console.error('获取商品失败:', error);
            alert('获取商品失败: ' + error.message);
        });
}

// 显示商品详情
function displayProductDetails(product) {
    currentProductId = product.id;
    
    document.getElementById('detail-id').textContent = product.id;
    document.getElementById('detail-product-code').textContent = product.productCode;
    document.getElementById('detail-product-name').textContent = product.productName;
    document.getElementById('detail-category-id').textContent = product.categoryId;
    document.getElementById('detail-unit').textContent = product.unit;
    document.getElementById('detail-cost-price').textContent = '¥' + (product.costPrice || 0).toFixed(2);
    document.getElementById('detail-sale-price').textContent = '¥' + (product.salePrice || 0).toFixed(2);
    document.getElementById('detail-stock-quantity').textContent = product.stockQuantity || 0;
    document.getElementById('detail-status').textContent = getStatusText(product.status);
    document.getElementById('detail-created-time').textContent = formatDateTime(product.createdTime);
    document.getElementById('detail-updated-time').textContent = formatDateTime(product.updatedTime);
    document.getElementById('detail-remark').textContent = product.remark || '';
    
    // 更新状态样式
    document.getElementById('detail-status').className = getStatusClassName(product.status);
    
    // 显示/隐藏操作按钮
    if (product.status === 'ACTIVE') {
        deactivateProductBtn.disabled = false;
        activateProductBtn.disabled = true;
    } else {
        deactivateProductBtn.disabled = true;
        activateProductBtn.disabled = false;
    }
    
    showSection(productDetailsSection);
}

// 上架商品
function activateProduct(productId) {
    fetch(`${API_BASE_URL}/${productId}/activate`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('上架商品失败');
        }
        return response.json();
    })
    .then(product => {
        alert('商品已上架');
        displayProductDetails(product);
        loadProducts();
    })
    .catch(error => {
        console.error('上架商品失败:', error);
        alert('上架商品失败: ' + error.message);
    });
}

// 下架商品
function deactivateProduct(productId) {
    fetch(`${API_BASE_URL}/${productId}/deactivate`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('下架商品失败');
        }
        return response.json();
    })
    .then(product => {
        alert('商品已下架');
        displayProductDetails(product);
        loadProducts();
    })
    .catch(error => {
        console.error('下架商品失败:', error);
        alert('下架商品失败: ' + error.message);
    });
}

// 删除商品
function deleteProduct(productId) {
    fetch(`${API_BASE_URL}/${productId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('删除商品失败');
        }
        alert('商品已删除');
        showSection(productListSection);
        loadProducts();
    })
    .catch(error => {
        console.error('删除商品失败:', error);
        alert('删除商品失败: ' + error.message);
    });
}

// 模拟商品数据
const mockProducts = [
    {
        id: 1,
        productCode: 'PROD001',
        productName: '智能手机A100',
        categoryId: 1,
        unit: '台',
        costPrice: 1500.00,
        salePrice: 2999.00,
        stockQuantity: 100,
        status: 'ACTIVE',
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString(),
        remark: '高端智能手机'
    },
    {
        id: 2,
        productCode: 'PROD002',
        productName: '笔记本电脑B200',
        categoryId: 2,
        unit: '台',
        costPrice: 3500.00,
        salePrice: 5999.00,
        stockQuantity: 50,
        status: 'ACTIVE',
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString(),
        remark: '商务笔记本电脑'
    },
    {
        id: 3,
        productCode: 'PROD003',
        productName: '平板电脑C300',
        categoryId: 1,
        unit: '台',
        costPrice: 1200.00,
        salePrice: 2499.00,
        stockQuantity: 80,
        status: 'INACTIVE',
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString(),
        remark: '入门级平板电脑'
    },
    {
        id: 4,
        productCode: 'PROD004',
        productName: '无线耳机D400',
        categoryId: 3,
        unit: '副',
        costPrice: 200.00,
        salePrice: 499.00,
        stockQuantity: 200,
        status: 'ACTIVE',
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString(),
        remark: '高音质无线耳机'
    }
];